<?php

/**
 * User: Baimingliang
 * Date: 2021/11/4
 * Time: 4:51 下午
 */

namespace app\admin\controller\cost;


use app\admin\model\CostBudgetDetail;
use app\admin\model\CostClassify;
use app\admin\model\CostCompany;
use app\admin\model\CostPurchaselist;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\upload\Uploadfile;
use jianyan\excel\Excel;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use think\App;



/**
 * Class BudgetDetail
 * @package app\admin\controller\cost
 * @ControllerAnnotation(title="预算详情")
 */

class BudgetDetail extends AdminController
{
    use Curd;
    public $classify;


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CostBudgetDetail();
        $this->classify = new CostClassify();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->withJoin(['classify','company','classifys'], 'LEFT')
                ->where($where)
                ->count();
            $list = $this->model
                ->withJoin(['classify','company','classifys'], 'LEFT')
                ->where($where)
                ->page($page, $limit)
                ->order(['budget_time' => 'desc'])
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();

            $rule = [
                'classify_id|所属分类'   => 'require',
                'budget_name|物品名称' => 'require',
                'budget_price|预算金额' => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $pid = CostClassify::where('id',$post['classify_id'])->value('pid');
                if($pid == 0){
                    $post['last_class_id'] = $post['classify_id'];
                }else{
                    $post['last_class_id'] = $pid;
                }
                $post['time'] = strtotime($post['time']);
                $post['budget_time'] = strtotime($post['time']);
                $save = $this->model->save($post);

            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }

        $pidMenuList = $this->classify->getPidMenuList();
        $CostCompanyArr = CostCompany::field('id,company_name')->where('status',2)->select()->toArray();
        array_shift($pidMenuList);
        $this->assign('pidMenuList', $pidMenuList);
        $this->assign('CostCompanyArr', $CostCompanyArr);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);

        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'classify_id|所属分类'   => 'require',
                'budget_name|物品名称' => 'require',
                'budget_price|预算金额' => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $pid = CostClassify::where('id',$post['classify_id'])->value('pid');
                if($pid == 0){
                    $post['last_class_id'] = $post['classify_id'];
                }else{
                    $post['last_class_id'] = $pid;
                }
                $post['budget_time'] = strtotime($post['time']);
                $post['time'] = strtotime($post['time']);
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $pidMenuList = $this->classify->getPidMenuList();
        $CostCompanyArr = CostCompany::field('id,company_name')->where('status',2)->select()->toArray();
        array_shift($pidMenuList);
        $row['time'] = date('Y-m-d',$row['time']);
        $this->assign('pidMenuList', $pidMenuList);
        $this->assign('row', $row);
        $this->assign('CostCompanyArr', $CostCompanyArr);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="上传")
     */
    public function  uploadFile(){
        set_time_limit(0);
        $data = [
            'upload_type' => 'local',
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        if ($upload['save'] == true) {
            $arr = Excel::import($upload['name']);
            unset($arr[1]);
            $company_name = CostCompany::field('id,company_name')->select()->toArray();
            $key = array_column($company_name,'id');
            $value = array_column($company_name,'company_name');
            $company_name_arr = array_combine($value,$key);
            $class_arr = CostClassify::field('id,title,pid')->select()->toArray();
            if($class_arr){
                foreach($class_arr as $key => $value){
                    if($value['pid'] == 0){
                        $class_last[] = $value;
                    }else{
                        $class_now[] = $value;
                    }
                }
                $class_key = array_column($class_last,'id');
                $class_value = array_column($class_last,'title');
                $class_name_arr = array_combine($class_value,$class_key);

                $class_now_key = array_column($class_now,'id');
                $class_now_value = array_column($class_now,'title');
                $class_now_name_arr = array_combine($class_now_value,$class_now_key);
            }
            foreach ($arr as $key => $value){
                $time = Date::excelToTimestamp(trim($value[2])) ?? time();
                $insert[] = [
                    'company_id' => $company_name_arr[$value[3]] ?? 0,
                    'time' => $time,
                    'budget_time' => $time,
                    'classify_id' => $class_arr ? $class_now_name_arr[trim($value[5])] ?? 0 : 0,
                    'last_class_id' => $class_arr ? $class_name_arr[trim($value[4])] ?? 0 : 0,
                    'budget_name' => trim($value[6]) ?? '',
                    'budget_price' => $value[7] ?? 0,
                    'budget_person' => trim($value[8]) ?? '',
                ];
            }
            $type = CostBudgetDetail::create_data($insert);
            if($type){
                return json(['code'=> 200,'msg' => '上传成功','data' => '']);
            }else{
                return json(['code'=> 500,'msg' => '上传失败','data' => '']);
            }


        } else {
            return json(['code'=> 500,'msg' => $upload['msg'],'data' => '']);
        }
    }

    /**
     * @NodeAnotation(title="下载模板")
     */
    public function downloadTpl(){
        $header = [
            ['序号','id'],
            ['月份','time'],
            ['预算支出日期','budget_time'],
            ['公司','company'],
            ['预算一级分类','a'],
            ['预算二级分类','b'],
            ['物品名称','c'],
            ['预算金额','d'],
            ['负责人','e'],
        ];
        $list = [
            [
                'id'=>1,
                'time' => '8月',
                'budget_time' => '2021/7/10',
                'company' => '北京总部',
                'a' => '员工福利',
                'b' => '员工福利 - 管理干部/其他',
                'c' => '蔡老师 颈椎按摩仪',
                'd' => '100',
                'e' => '测试人',
            ]
        ];
        return Excel::exportData($list, $header, '预算详情模板', 'xlsx');
    }



}